package com.lt.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lt.utils.JwtUtils;
import com.lt.utils.Result;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;

/**
 * @Author :liteng
 * @Time : 2023-10-22 22:40
 */

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override//返回 true，放行 false：不放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        System.out.println("执行了preHandle");
        response.setContentType("text/html;charset=utf-8");
//        HttpServletRequest req = (HttpServletRequest) servletRe

        String requestURI = request.getRequestURI();
        /*
        String jwt = request.getHeader("token");

        Result error = Result.error("登录状态失效");

        if (!StringUtils.hasLength(jwt)) {
            log.info("未登录");
//            JSONObject jsonObject = new JSONObject(true);
            String jsonString = JSONObject.toJSONString(error, SerializerFeature.PrettyFormat,
                    SerializerFeature.WriteMapNullValue);
//            response.getWriter().write(jsonString);
            //将校验关闭
            return true;

        }

         */

        /*
        try {
            Claims claims = JwtUtils.parseJwt(jwt);
            Long num = (Long)claims.get("num");
            log.error(String.valueOf(num));

        } catch (Exception e) {
            e.printStackTrace();
            log.info("令牌解析失败");
//            Result error = Result.error("登录状态失效");
            String jsonString = JSONObject.toJSONString(error, SerializerFeature.PrettyFormat,
                    SerializerFeature.WriteMapNullValue);
//            response.getWriter().write(jsonString);
            //将校验关闭
            return true;
//            throw new RuntimeException(e);
        }

         */

        log.info("放行");
        return true;
//        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
